const _ = require("lodash");

function select32NumbersByS7(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  // ✅ 定义多个窗口
  const windowSizes = [5, 9, 13];
  const voteMap = {};

  // 🧠 所有窗口预测 -> 票数累积
  for (const w of windowSizes) {
    const t = temp.slice(-w);
    const countMap = _.countBy(t.map((v) => v.number));
    const topNumbers = Object.entries(countMap)
      .sort((a, b) => b[1] - a[1])
      .map((x) => x[0])
      .slice(0, 20); // 每个窗口最多投20票

    topNumbers.forEach((n) => {
      voteMap[n] = (voteMap[n] || 0) + 1;
    });
  }

  // 📉 连错淘汰机制：最近5期从未出现的号，降票
  const recentWrongSet = new Set();
  for (let i = temp.length - 5; i < temp.length; i++) {
    if (i < 0) continue;
    recentWrongSet.add(temp[i].number);
  }

  for (const num of Object.keys(voteMap)) {
    if (!recentWrongSet.has(num)) {
      voteMap[num] -= 1.5; // 惩罚冷号
    }
  }

  // 💡 奇偶控制与补全
  const sortedNumbers = Object.entries(voteMap)
    .filter(([, v]) => v > 0)
    .sort((a, b) => b[1] - a[1])
    .map(([n]) => n);

  let finalNumbers = sortedNumbers.slice(0, 32);

  // ✨ 补全不够时：补周期短 + 错误少的号
  if (finalNumbers.length < 32) {
    const appearMap = {};
    for (let i = temp.length - 60; i < temp.length; i++) {
      if (i < 0) continue;
      const n = temp[i].number;
      appearMap[n] = i;
    }

    const scored = allNumbers
      .filter((n) => !finalNumbers.includes(n))
      .map((n) => {
        const recentIndex = appearMap[n] || 0;
        const interval = temp.length - recentIndex;
        return { n, score: 1000 / interval };
      })
      .sort((a, b) => b.score - a.score)
      .map((x) => x.n);

    finalNumbers = finalNumbers.concat(scored.slice(0, 32 - finalNumbers.length));
  }

  // 🎯 奇偶比例调整
  const even = finalNumbers.filter((x) => parseInt(x) % 2 === 0);
  const odd = finalNumbers.filter((x) => parseInt(x) % 2 === 1);

  if (even.length > 20) {
    finalNumbers = even.slice(0, 16).concat(odd.slice(0, 16));
  }

  return finalNumbers.slice(0, 32);
}

module.exports = select32NumbersByS7;
